const data = {
    name: 'ctx',
    age:18,
    test:{
        name:"aaa",
        grade:100
    },
    arr:[1,2,1000]
};

const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
['pop','push','shift','unshift','splice','sort','reverse'].forEach(method => {
    arrayMethods[method] = function () {
        arrayProto[method].call(this,...arguments);
        render();
    }
});

function observer(data) {
    if(Array.isArray(data)){
        data.__proto__ = arrayMethods;
        return;
    }
    if(typeof data === 'object'){
        for(let key in data){
            defineReactive(data,key,data[key]);
        }
    }
}

function defineReactive(data ,key , value){
    observer(value);
    Object.defineProperty(data,key,{
        get() {
            // console.log("du");
            return value;
        },
        set(v) {
            // console.log("写");
            if(value === v){
                return;
            }
            value = v;
            render();
        }
    })
}
function $set(data,key,value) {
    if(Array.isArray(data)){
        data.splice(key,1,value);
        return value;
    }
     defineReactive(data,key,value);
     render();
     return value;
}
function $delete(data,key) {
    if(Array.isArray(data)){
        data.splice(key,1);
        return;
    }
    delete data[key];
    render();
}
function render() {
    console.log("页面渲染了");
}
observer(data);
// console.log(data.age);
//
// data.age = 16;
// console.log(data.age);
// data.test.name = "CET4";
// console.log(data.test.name);
data.arr.push(200);
data.arr.reverse();
$set(data.arr,0,2000);
$delete(data.arr,3);
console.log(data.arr);

// var obj = {
//
// };
// obj.log = console.log;
// obj.log.call(console,this);
